$(document).ready(function(){
    //调用datepicker插件
    $('#datePicker').daterangepicker();
    //按客户类型屏蔽多选按钮
    $(".customer-name").on("click",function(){
    	$(this).toggleClass('on');
    	if($(this).hasClass('on')){
    		$(this).next('input').attr('checked',true);
    	}else{
    		$(this).next('input').attr('checked',false);
    	}
        var item=$('.customer-name');
        var count=0;
        $(item).each(function(){
        	if($(this).hasClass('on')){
        		count++;
        	}
        });
        if(count==item.length){
        	$(".customer-all").addClass('on');
        }else{
        	$(".customer-all").removeClass('on');
        };
        $('.customer-type input').each(function(){
        	if($(this).attr('checked')){
        		console.log($(this).val());
        	}
        });
    });
    //全部选中
    $(".customer-all").click(function(){
    	var level=$('.customer-name');
        $(this).toggleClass('on');
        if($(this).hasClass('on')){
        	$(level).each(function(){
        		$(this).addClass('on').next('input').attr('checked',true);
        	})
        }else{
        	$(level).each(function(){
        		$(this).removeClass('on').next('input').attr('checked',false);
        	})
        };
    });
    
    //单选、全选
    $(function (){
        $("table tbody").on('click', 'tr td s', function () {
            $(this).toggleClass('selected');
        })
    });
    $("table thead tr").on('click', 'td s', function () {
        var item=$(this).parent().parent().parent().siblings('tbody').children('tr').find('s');
        if(!$(this).hasClass('selected')){
            $(this).addClass('selected');
            item.addClass('selected');
        }else{
            $(this).removeClass('selected');
            item.removeClass('selected');
        }
    });
    //详情、修改、删除
    $('table').on('click','tbody tr td button',function(e){
    	e.preventDefault();
    });
    $(function () {
        $("table tbody").on('click', 'tr td .detail', function (e) {
            e.stopPropagation();
            e.preventDefault();
            console.log('s');
        });
        $("table tbody").on('click', 'tr td .revise', function (e) {
            e.stopPropagation();
            e.preventDefault();
            console.log('sfsfds');
        });
        $("table tbody").on('click', 'tr td .delete', function (e) {
            e.stopPropagation();
            e.preventDefault();
            $('#mask-box').css('display','block').children('#remove-block').css('display','block');
        });
    });
    
    //批量删除
    $('.delete-more').click(function(){
        $('#mask-box').css('display','block').children('#remove-block').css('display','block');
    });
    $('body').on('click','.applyBtn',function(){
       var date = $('#datePicker').val();
       console.log(date);
       arr=date.split(" - "); 
       var startDate = arr[0];
       var endDate = arr[1];
       $("#startdate").val(startDate);
       $("#enddate").val(endDate);
       $.ajax({
    	   url:"checkTime",
    	   type:"post",
    	   data:{"startTime":startDate},
    	   dataType:"json",
    	   success:function(data){
    		   if(data == 0){
    			   //时间冲突,不能新增
    			   alertBox(0,"该时间已有活动,请更换时间");
    			   $("#next").attr("disabled","disabled");
    		   }else if(data == 1){
    			   $("#next").removeAttr("disabled");
    		   }
    	   }
       })
    });
    
    $('.tab').on('click','div',function(){
    	var divId = $(this).attr('id');
    	if(activityType == '修改活动'){
    		if(divId == 'msg'){
    			var id = $(this).attr('data-id');
    			window.location.href = "/DistributorSystem/productActivity/gotoUpdateActivity?id="+id+"&activityType="+activityType;
    		}else if(divId == 'chose-product'){
    			var id = $(this).attr('data-id');
    			window.location.href = "/DistributorSystem/productActivity/gotoActivityProduct?id="+id+"&activityType="+activityType;
    		}else if(divId == 'revise'){
    			var id = $(this).attr('data-id');
    			window.location.href = "/DistributorSystem/productActivity/gotoActivityProductPrice?id="+id+"&activityType="+activityType;
    		}
    	}
    })
    
    $('#reset').click(function(){
    	window.location.href = "/DistributorSystem/productActivity/listActivity";
    })
    
    
});
function changeProvince(){
	var provinceId = $('#province').val();
	//alert(provinceId);
	$.ajax({
		type:"post",
		url:"findCitys",
		data:{"provinceId":provinceId},
		dateType:"json",
		success:function(data){
			var info = "<option value='0'>全部市</option>";
			for(var i=0;i<data.length;i++){
				var cityId = data[i].id;
				var cityName = data[i].name;
				info += "<option value='"+cityId+"'>"+cityName+"</option>";
			}
			$("#city").html(info);
		}
	})
}

function getProduct(){
	var condition = $("#condition").val();
	var warehouse = $("#warehouse").val();
	var productActivityId = $("#productActivityId").val();
	$.ajax({
        url: "getProductByCondition",
        type: "POST",                       //请求方式
        data:{condition:condition,productActivityId:productActivityId},
        dataType: "json",
        success: function (result,obj) {
        	$(".chose-form tbody").children("tr").remove();
        	var html="";
        	var productList = result.obj
        	for (var int = 0; int < productList.length; int++) {
				html+="<tr id="+productList[int].id+"><td><s></s></td><td><div><img src='"+productList[int].photoHref+"'/></div></td><td><p>"+(productList[int].code==undefined?"":productList[int].code)+"</p><p>"+(productList[int].productName==undefined?"":productList[int].productName)+"</p><p>"+(productList[int].brandName==undefined?"":productList[int].brandName)+"</p></td><td>"+(productList[int].groupSpecValue==undefined?"":productList[int].groupSpecValue)+"</td><td>"+(productList[int].standard==undefined?"":productList[int].standard)+"</td><td>"+(productList[int].price.toFixed(2)==undefined?"":productList[int].price.toFixed(2))+"/"+(productList[int].littleUnit==undefined?"":productList[int].littleUnit)+"</td><td>"+(productList[int].orderedPrice.toFixed(2)==undefined?"":productList[int].orderedPrice.toFixed(2))+"/"+(productList[int].littleUnit==undefined?"":productList[int].littleUnit)+"</td><td>"+(productList[int].purchasePrice.toFixed(2)==undefined?"":productList[int].purchasePrice.toFixed(2))+"/"+(productList[int].littleUnit==undefined?"":productList[int].littleUnit)+"</td><td><button class='add-product' onclick='addProduct(this)'>增加</button><button class='detail' onclick='productDetail("+(productList[int].id==undefined?"":productList[int].id)+")'>详情</button></td></tr>"
			}
        	$(".chose-form tbody").html(html);
        },
        fail: function (result) {
            // 此处放失败后执行的代码
        }
    });
}
/**
 * 添加活动商品
 */
function addProduct(q){
	var addButton = $(q);
	console.log(addButton);
	var productPriceId = $(q).parent().parent('tr').attr('id');
	var productActivityId = $("#productActivityId").val();
	$.ajax({
        url: "insertActivityProductByProductId",
        type: "POST",                       //请求方式
        data:{productPriceId:productPriceId,productActivityId:productActivityId},
        dataType: "json",
        success: function (result,obj) {
        	console.log(result);
        	if(result.status){
        		addButton.html("已添加");
        		addButton.attr('disabled',true);
        		addButton.addClass('disabled');
        		alertBox(1,"添加成功!");
        		$(q).parent().parent('tr').html('');
        	} else{
        		alertBox(0,"添加失败!");
        	}
        },
        fail: function (result) {
            // 此处放失败后执行的代码
        }
    });
}
/**
 * 删除活动商品
 */
function deleteActivityProduct(id,activityId,that){
	var that = $(that).parent("td").parent("tr");
	$(".queren").on('click', function (e) {
	    e.stopPropagation();
	    e.preventDefault();
	    $.ajax({
	        url: "deleteActivityProductByProductId",
	        type: "POST",                       //请求方式
	        data:{id:id,activityId:activityId},
	        dataType: "json",
	        success: function (result,obj) {
	        	if(result.status){
	        		that.remove();
	        		$('#mask-box').css('display','none');
	        		alertBox(1,"删除成功");
	        	} else{
	        		alertBox(0,"删除失败");
	        	}
	        },
	        fail: function (result) {
	            // 此处放失败后执行的代码
	        }
	    });
	});
}
/**
 * 商品详情
 */
function productDetail(id){
	window.open("/DistributorSystem/product/findProductInfo?id="+id);
}


function updateActivityProduct(q){
	var params = {};
	params.id = $(q).parent().parent('tr').attr('id');
	params.productActivityId = $("#productActivityId").val();
	params.activityPrice = $(q).parent().parent().find('input')[0].value;
	params.totalLimit = $(q).parent().parent().find('input')[1].value;
	params.personLimit = $(q).parent().parent().find('input')[2].value;
	var updateButton = $(q);
	console.log(params);
	$.ajax({
        url: "updateActivityProductByProductId",
        type: "POST",//请求方式
        data:params,
        dataType: "json",
        success: function (result,obj) {
        	console.log(result);
        	if(result.status){
        		alertBox(1,"修改成功!");
        	} else{
        		alertBox(0,"修改失败!");
        	}
        },
        error: function (result) {
        	alertBox(0,"请正确填写空格里的数据!!!");
        }
    });
}
//点击取消隐藏删除对话框
$(".cancel").on('click', function (e) {
    e.stopPropagation();
    e.preventDefault();
    $('#mask-box').css('display','none');
});
//选择图片，马上预览
function changeName(obj) {
    var file = obj.files[0];
//    console.log(obj);console.log(file);
//    console.log("file.size = " + file.size);  //file.size 单位为byte
      var reader = new FileReader();
//    //读取文件过程方法
//    reader.onloadstart = function (e) {
//        console.log("开始读取....");
//    }
//    reader.onprogress = function (e) {
//        console.log("正在读取中....");
//    }
//    reader.onabort = function (e) {
//        console.log("中断读取....");
//    }
//    reader.onerror = function (e) {
//        console.log("读取异常....");
//    }
    reader.onload = function (e) {
       // console.log("成功读取....");
        var img = document.getElementById("yulanImg");
        img.src = e.target.result;
        //或者 img.src = this.result;  //e.target == this
    }
    reader.readAsDataURL(file)
}